import { TDatasetServices } from "./datasetServices"
import { TDbServices } from "./dbServices"
import { TSqlAnalyzeService } from "./sqlAnalyzeServices"


export type TUtilsService = ReturnType<typeof getServices>


export function getServices(
    datasetServices: TDatasetServices,
    sqlAnalyze: TSqlAnalyzeService,
    dbServices: TDbServices) {

    function createSqlQuery(
        cpID: string,
        sql: string,) {

        const tables = sqlAnalyze.getTableNames(sql)

        function query() {
            let sqlCopy = sql

            return dbServices.runOnTransaction(() => {
                tables.forEach(table => {
                    const sourceSql = datasetServices.createSql(table, cpID)
                    sqlCopy = sqlAnalyze.replaceTableToFilterQuery(sqlCopy, table, sourceSql.value)
                })
                return dbServices.queryAll(sqlCopy)
            }, 'ROLLBACK')
        }

        return {
            query
        }
    }

    return {
        createSqlQuery
    }
}